import { ProjectModel } from 'major-schedulerpro'
import DefaultScheduler from './index'
import featuresCommon from './config/features'
import { addEvents } from './utils'
import CustomEventModel from './baseClass/MajorEventModel'

// import { handleKeyPoint } from '@/mixin/gantt'
/**
 * 工作区
 *   partner: this.scheduler,
 *
 * 拖拽 只有事件含有 fillEventRecordType  属性的事件才可以拖拽进入释放数据
 *
 * 只有设置了 draggable:true 的事件才可以拖动
 *
 */
export default class workSpaceScheduler {
  constructor(opt) {
    this.container = opt.container
    this.standardTime = opt.standardTime
    this.partner = opt.partner
    this.partnerEngine = opt.partnerEngine
    // 初始化资源负荷图
    // this.initScheduler()
  }
  container = null
  scheduler = null
  // 合作者
  partner = null
  partnerEngine = null
  isDragging = false
  // 当前拖动进入的事件
  dragOverEventRecord = null
  standardTime = +new Date()
  // 事件
  eventDatas = []
  // 泳道
  laneDatas = [
    {
      id: 1,
      name: '任务作业编辑区',
      expanded: true,
      children: [
        {
          id: 2,
          name: '通信保障任务',
        },
        {
          id: 3,
          name: '通信接入',
        },
        {
          id: 4,
          name: '能力提供',
        },
      ],
    },
  ]
  // 关系
  dependencies = []
  initScheduler() {
    const project = this.getSchedulerProjectModel()
    this.scheduler = DefaultScheduler.renderCommonScheduler(
      {
        appendTo: this.container,
        project: project,
        partner: this.partner,
        ref: 'workSpaceScheduler',
        height: '420px',
        // rowHeight: 80,
        hideHeaders: true,
        columns: [
          {
            type: 'tree',
            width: 200,
            height: 300,
            showColumnPicker: false,
            leafIconCls: null,
            indentSize: 3,
            expandIconCls: 'b-fa b-fa-plus',
            collapseIconCls: 'b-fa b-fa-minus',
            sortable: false,
            // sum: 'count',
            htmlEncode: false,
            renderer: ({ record }) => {
              return record.name
            },
            /* headerRenderer: () => {
              return '<div  class="calendar-header">任务规划</div>'
            } */
          },
        ],
        features: this.getWorkspaceFeatures(),
        listeners: this.getWorkspapceListeners(),
      },
      this.standardTime
    )
  }
  /**
   * 获取projectModel
   * @returns
   */
  getSchedulerProjectModel() {
    return new ProjectModel({
      eventsData: this.eventDatas,
      resourcesData: this.laneDatas,
      dependenciesData: this.dependencies,
      eventModelClass: CustomEventModel,
      listeners: {
        load: () => {
          console.log('加载完毕')
        },
      },
    })
  }
  /**
   * 工作区 功能配置
   */
  getWorkspaceFeatures() {
    const that = this
    const curFeatures = Object.assign({}, featuresCommon(this.standardTime), {
      dependencies: false,
      scheduleMenu: false, // 右键新增菜单
      eventMenu: {
        items: {
          editEvent: {
            weight: 1,
            text: '修改',
            onItem: ({ eventRecord }) => {
              that.modifyChainData(eventRecord)
            },
          },
          finish: {
            weight: 2,
            text: '完成',
            onItem: ({ eventRecord }) => {
              that.finishPlaning(eventRecord)
            },
          },
          deleteEvent: false,
          unassignEvent: false,
        },
        processItems({ eventRecord, items }) {
          console.log(items, eventRecord)
          /**
           * 根据当前事件 customEventType  控制右键菜单的显示状态
           * workSpace  右键菜单 ‘完成’
           * transmit  ‘修改’
           */
          const customEventType = eventRecord.get('customEventType'),
            itemEnum = {
              transmit: ['editEvent'],
              workSpace: ['finish'],
            },
            crrentEventMenus = itemEnum?.[customEventType] ?? []
          items.finish.hidden = !crrentEventMenus.includes('finish')
          items.editEvent.hidden = !crrentEventMenus.includes('editEvent')
        },
      },
      eventDrag: {
        // constrainDragToResource: true,
        showTooltip: false,
      },
    })

    return curFeatures
  }
  /**
   * 监听事件
   * @returns
   */
  getWorkspapceListeners() {
    const that = this
    return {
      beforeEventDrag() {
        that.isDragging = true
      },
      afterEventDrop({ eventRecords }) {
        if (that.isDragging) {
          that.setDragOverEventRecordStyle(false, '.allow-drop-container')
          that.isDragging = false
          /**
           * 将当前的事件绑定到 填充改的事件中
           *  只有存在 fillEventRecordType 的事件才可以拖拽进入
           */
          if (that.dragOverEventRecord) {
            const fillEventRecordType = that.dragOverEventRecord.get(
              'fillEventRecordType'
            )
            if (!fillEventRecordType) {
              console.log('当前事件不是可填充的节点数据')
            }
            /**
             * 当前填充的数据是否含有关键点的信息
             * 主要是通信车类型的关键点
             */

            that.updateTransmitKeyKPoint(that.dragOverEventRecord.id, [
              eventRecords[0].originalData,
            ])
            /*  const statusInformation = eventRecords[0].get('statusInformation')
  let otherAttr = {}
  if (statusInformation) {
    otherAttr.keyPoint = statusInformation
  }
  that.dragOverEventRecord.set({
    // describe: eventRecords[0].get('describe'),
    // 链路数据
    fillEventRecord: {
      chainData: [
        {
          id: that.partnerEngine.uuid(),
          name: eventRecords[0].name,
          startDate: eventRecords[0].startDate,
          endDate: eventRecords[0].endDate,
          fillEventRecordData: eventRecords[0],
          ...otherAttr
        }
      ]
    }
  }) */
            that.dragOverEventRecord = null
            /**
             * 当数据填充完毕时 查看 接入、服务是否都已经填充过
             * 当都填充过时 将 id：transmit  的事件填充数据
             */
            that.setTransmitFillEventRecord()
          }
        }
      },
      /**
       * 拖拽释放时 拒绝此次调整
       * @param {*} param0
       */
      beforeEventDropFinalize({ context }) {
        /*  console.log(that.dragOverEventRecord)
        if (that.dragOverEventRecord) {
          context.async = false
          context.finalize(false)
        } else {
          context.async = true
          context.finalize(true)
        } */
        context.async = false
        context.finalize(false)
        if (that.isDragging) {
          that.isDragging = false
          that.setDragOverEventRecordStyle(false, '.allow-drop-container')
        }
      },
      /**
       * 当拖拽时 进入到可以释放的节点 （fillEventRecordType）
       * 通过改变eventStyle 设置醒目样式
       * @param {*} param0
       */
      eventMouseOver({ eventRecord }) {
        console.log('进入了')
        const fillEventRecordType = eventRecord.get('fillEventRecordType')
        if (that.isDragging && fillEventRecordType) {
          that.dragOverEventRecord = eventRecord
          const { id } = eventRecord
          that.setDragOverEventRecordStyle(true, "[data-event-id='" + id + "']")
        }
      },
      /**
       * 当鼠标移出事件时 如果是正在拖拽中
       * 并且当前事件是可以释放的 重新设置eventStyle
       * @param {*} param0
       */
      eventMouseOut({ eventRecord }) {
        const fillEventRecordType = eventRecord.get('fillEventRecordType')
        if (that.isDragging && fillEventRecordType) {
          const { id } = eventRecord
          // 当前可拖拽释放事件置空
          that.dragOverEventRecord = null
          that.setDragOverEventRecordStyle(
            false,
            "[data-event-id='" + id + "']"
          )
        }
      },
    }
  }
  /**
   * 当拖拽填充了接入 或者服务 时 查看是否都填充过数据了
   * 都填充完毕时 transmit 节点添加填充数据
   */
  setTransmitFillEventRecord() {
    const { accessStoreChainData, transmitStore, servicesStoreChainData } =
      this.getFillEventRecordData()
    if (accessStoreChainData && servicesStoreChainData) {
      this.updateTransmitKeyKPoint('transmit', [
        {
          id: 'gojsLaneKj', // this.partnerEngine.uuid(),
          name: '翔龙无人侦察机',
          startDate: transmitStore.startDate,
          endDate: transmitStore.endDate,
          statusInformation: [
            {
              name: '机动',
            },
            {
              name: '开机',
            },
            {
              name: '静默',
            },
          ],
        },
      ])
      /*
      transmitStore.set({
        // 链路数据
        fillEventRecord: {
          chainData: [
            {
              id: this.partnerEngine.uuid(),
              name: 'kj5000',
              startDate: transmitStore.startDate,
              endDate: transmitStore.endDate,
              fillEventRecordData: transmitStore
            }
          ]
        }
      }) */
    }
  }

  /**
   * 获取填充数据
   */
  getFillEventRecordData() {
    const accessStore = this.scheduler.eventStore.getById('access'),
      transmitStore = this.scheduler.eventStore.getById('transmit'),
      servicesStore = this.scheduler.eventStore.getById('services'),
      accessStoreChainData = accessStore.get('fillEventRecord'),
      transmitStoreChainData = transmitStore.get('fillEventRecord'),
      servicesStoreChainData = servicesStore.get('fillEventRecord')
    return {
      accessStoreChainData,
      transmitStoreChainData,
      servicesStoreChainData,
      transmitStore,
    }
  }
  /**
   * 添加事件
   * @param {Array | Object} events 数组或者object类型
   */
  addEvents(events) {
    addEvents(this.scheduler, events)
  }
  /**
   * 控制拖拽已入时的样式
   * @param {*} isActive
   * @param {*} selector
   */
  setDragOverEventRecordStyle(isActive, selector) {
    const _ele = document.querySelector(selector)
    if (_ele) {
      isActive
        ? _ele.classList.add('allow-drop-container')
        : _ele.classList.remove('allow-drop-container')
    }
  }
  /**
   * 完成当前的规划
   */
  finishPlaning(eventRecord) {
    /**
     * 找到规划的事件中使用的通信设备
     * id 分别为 access transmit services
     */
    const {
      accessStoreChainData,
      transmitStoreChainData,
      servicesStoreChainData,
    } = this.getFillEventRecordData()
    if (
      !accessStoreChainData ||
      !transmitStoreChainData ||
      !servicesStoreChainData
    ) {
      return
    }
    const { chainData: accessChainData } = accessStoreChainData,
      { chainData: transmitChainData } = transmitStoreChainData,
      { chainData: servicesChainData } = servicesStoreChainData
    // 处理当前时间与目标时间一致
    this.handleEndDate(accessChainData, eventRecord.originalData)
    this.handleEndDate(transmitChainData, eventRecord.originalData)
    this.handleEndDate(servicesChainData, eventRecord.originalData)
    const links = [
      ...accessChainData,
      ...transmitChainData,
      ...servicesChainData,
    ]
    // 点击完成处理原始数据链路
    this.handleOriginLink(eventRecord, links)
    // 将使用的数据回填值上方负荷图
    console.log('accessChainData, transmitChainData, servicesChainData')
    console.log(accessChainData, transmitChainData, servicesChainData)
    this.partnerEngine.renderWorkData({
      accessChainData,
      transmitChainData,
      servicesChainData,
    })
  }
  /**
   * 获取结束时间
   */
  handleEndDate(data, targetData) {
    for (const item of data) {
      item.startDate = targetData.startDate
      item.endDate = targetData.endDate
      console.log(item)
      // if (item.keyPoint) {
      // const _item = {
      //   startTime: item.startDate,
      //   endTime: item.endDate
      // }
      // item.keyPoint = handleKeyPoint(item.keyPoint, _item)
      // }
    }
  }
  // 处理链路
  handleOriginLink(data, links) {
    console.log('*********link*********')
    const linkId = data.id + '_link'
    this.partnerEngine.scheduler.trigger('setLinkData', { id: linkId, links })
  }
  /**
   * 修改链路
   * @param {*} eventRecord
   */
  modifyChainData(eventRecord) {
    this.partnerEngine.modifyChainData(eventRecord)
  }
  /**
   * 更新链路数据
   * @param {*} chainData
   */
  updateTransmitKeyKPoint(key, chainData) {
    const transmitStore = this.scheduler.eventStore.getById(key)
    let _chainData = []
    for (const item of chainData) {
      const { statusInformation } = item
      // 是否含有关键点信息
      let otherAttrs = {}
      statusInformation && (otherAttrs.keyPoint = statusInformation)
      _chainData.push({
        id: item.id,
        name: item.name,
        // 缺失开始、结束时间
        startDate: transmitStore.startDate,
        endDate: transmitStore.endDate,
        // 关键点信息 时间
        ...otherAttrs,
      })
    }

    transmitStore.set({
      // 链路数据
      fillEventRecord: {
        chainData: _chainData,
      },
    })
  }
  /**
   * 模拟通信接入 服务提供者
   */
  mockInfoAndServeData() {
    const stores = [
      {
        id: 'txzhc',
        name: '潮州JY机场',
        startDate: '2023-05-24 01:00:00',
        endDate: '2023-05-24 04:00:00',
        resourceId: 3,
        draggable: true,
        // 通信车的机动信息 开机 机动...
        statusInformation: [
          {
            name: '开机',
          },
          {
            name: '开机',
          },
        ],
        describe: [
          {
            name: '短',
            eventColor: '#009180',
          },
          {
            name: '卫',
            eventColor: '#999999',
          },
        ],
      },
      {
        id: 'zx01',
        name: '建陵南雷达站',
        startDate: '2023-05-24 01:00:00',
        endDate: '2023-05-24 02:00:00',
        resourceId: 3,
        draggable: true,
        statusInformation: [
          {
            name: '机动',
          },
          {
            name: '开机',
          },
          {
            name: '静默',
          },
        ],
        describe: [
          {
            name: '数',
            eventColor: '#009180',
          },
          {
            name: '卫',
            eventColor: '#999999',
          },
        ],
      },
      {
        id: 'wrczj',
        name: '彩虹7',
        startDate: '2023-05-24 01:00:00',
        endDate: '2023-05-24 06:00:00',
        resourceId: 4,
        draggable: true,
        statusInformation: [
          {
            name: '机动',
          },
          {
            name: '开机',
          },
          {
            name: '静默',
          },
        ],
        describe: [
          {
            name: '目卫',
            eventColor: '#999999',
          },
        ],
      },
    ]

    this.addEvents(stores)
  }
}
